/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.cn.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.cn.entity.AttendanceCn;
import com.thinkgem.jeesite.modules.cn.service.AttendanceCnService;

/**
 * 中国考勤Controller
 * 
 * @author hui.li
 * @version 2017-02-20
 */
@Controller
@RequestMapping(value = "${adminPath}/cn/attendanceCn")
public class AttendanceCnController extends BaseController {

	@Autowired
	private AttendanceCnService attendanceCnService;

	@ModelAttribute
	public AttendanceCn get(@RequestParam(required = false) String id) {
		AttendanceCn entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = attendanceCnService.get(id);
		}
		if (entity == null) {
			entity = new AttendanceCn();
		}
		return entity;
	}

	@RequiresPermissions("cn:attendanceCn:view")
	@RequestMapping(value = { "list", "" })
	public String list(@RequestParam(required = true) String warehouse,
			AttendanceCn attendanceCn, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		// 设置仓库
		if (null != warehouse && warehouse.length() > 0) {
			attendanceCn.setWarehouse(warehouse);
		}
		Page<AttendanceCn> page = attendanceCnService.findPage(
				new Page<AttendanceCn>(request, response), attendanceCn);
		model.addAttribute("page", page);
		model.addAttribute("warehouse", warehouse);
		return "modules/cn/attendanceCnList";
	}

	@RequiresPermissions("cn:attendanceCn:view")
	@RequestMapping(value = "form")
	public String form(AttendanceCn attendanceCn, Model model) {
		model.addAttribute("attendanceCn", attendanceCn);
		return "modules/cn/attendanceCnForm";
	}

	@RequiresPermissions("cn:attendanceCn:edit")
	@RequestMapping(value = "save")
	public String save(AttendanceCn attendanceCn, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, attendanceCn)) {
			return form(attendanceCn, model);
		}
		attendanceCnService.save(attendanceCn);
		addMessage(redirectAttributes, "保存中国考勤成功");
		return "redirect:" + Global.getAdminPath() + "/cn/attendanceCn/?repage";
	}

	@RequiresPermissions("cn:attendanceCn:edit")
	@RequestMapping(value = "delete")
	public String delete(AttendanceCn attendanceCn,
			RedirectAttributes redirectAttributes) {
		attendanceCnService.delete(attendanceCn);
		addMessage(redirectAttributes, "删除中国考勤成功");
		return "redirect:" + Global.getAdminPath() + "/cn/attendanceCn/?repage";
	}

	/**
	 * 导入考勤数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("cn:attendanceCn:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,
			RedirectAttributes redirectAttributes, AttendanceCn attendanceCn) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + Global.getAdminPath()
					+ "/cn/attendanceCnList/list?warehouse="
					+ attendanceCn.getWarehouse();
		}
		try {
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<AttendanceCn> list = ei.getDataList(AttendanceCn.class);
			for (AttendanceCn at : list) {
				try {
					BeanValidators.validateWithException(validator, at);
					at.setWarehouse(attendanceCn.getWarehouse());
					String workingHours = at.getWorkingHours();
					if (null != workingHours && workingHours.length() > 0) {
						Double hours = Double.valueOf(workingHours);
						// 当天考勤工时>0的记录计入出勤人数；（工时工时为0，或空格，或文字的都不应计入人数）
						if (hours > 0) {
							attendanceCnService.save(at);
						}
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append(" 导入失败：");
					continue;
				} catch (Exception ex) {
					failureMsg.append("导入失败：" + ex.getMessage());
					continue;
				}
			}
			addMessage(redirectAttributes, "已成功导入 ");
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入考勤失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/cn/attendanceCn/list?warehouse="
				+ attendanceCn.getWarehouse();
	}

	/**
	 * 下载导入考勤数据模板
	 * 
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("cn:attendanceCn:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "仓库考勤.xlsx";
			List<AttendanceCn> list = Lists.newArrayList();
			list.add(attendanceCnService.get("22"));
			new ExportExcel("仓库考勤", AttendanceCn.class, 2).setDataList(list)
					.write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/cn/attendanceCnList/list?repage";
	}

	/**
	 * 导出考勤数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("cn:attendanceCn:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(@RequestParam(required = true) String warehouse,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, AttendanceCn attendanceCn) {
		try {
			// 设置仓库
			if (null != warehouse && warehouse.length() > 0) {
				attendanceCn.setWarehouse(warehouse);			
			}
			String fileName = "国内仓库考勤数据" + DateUtils.getDate("yyyyMMddHHmmss")
					+ ".xlsx";
			Page<AttendanceCn> page = attendanceCnService
					.findPage(new Page<AttendanceCn>(request, response, -1),
							attendanceCn);
			new ExportExcel("国内仓库考勤数据", AttendanceCn.class)
					.setDataList(page.getList()).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/cn/attendanceCnList/?repage";
	}

}